import uuid
import asyncio
from datetime import datetime
from typing import List

from sqlalchemy import String, DateTime, ForeignKey, Boolean, UniqueConstraint, UUID
from sqlalchemy.orm import DeclarativeBase
from sqlalchemy.orm import Mapped, mapped_column, relationship


class Base(DeclarativeBase):
    pass


class Tender(Base):
    __tablename__ = "tenders"
    __table_args__ = (
        UniqueConstraint("category", "quarter", name="uq_category_quarter"),
    )

    id: Mapped[uuid.UUID] = mapped_column(
        UUID, primary_key=True, default=uuid.uuid4
    )
    # 基本属性
    category: Mapped[str] = mapped_column(String(50))
    quarter: Mapped[str] = mapped_column(String(50))
    # 时间
    created_at: Mapped[datetime] = mapped_column(
        DateTime, default=datetime.now
    )
    updated_at: Mapped[datetime] = mapped_column(
        DateTime, default=datetime.now, onupdate=datetime.now
    )

    # relationships
    tender_document: Mapped["TenderDocument"] = relationship(
        back_populates="tender", cascade="all, delete-orphan"
    )
    bid_documents: Mapped[List["BidDocument"]] = relationship(
        back_populates="tender", cascade="all, delete-orphan"
    )


class TenderDocument(Base):
    __tablename__ = "tender_documents"

    id: Mapped[uuid.UUID] = mapped_column(
        UUID, primary_key=True, default=uuid.uuid4
    )
    # 基本属性
    original_name: Mapped[str] = mapped_column(String(128))
    file_path: Mapped[str] = mapped_column(String(256))
    tendering_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenders.id"))

    # relationship
    tender: Mapped["Tender"] = relationship(back_populates="tender_document")


class BidDocument(Base):
    __tablename__ = "bid_documents"

    id: Mapped[uuid.UUID] = mapped_column(
        UUID, primary_key=True, default=uuid.uuid4
    )
    # 基本属性
    name: Mapped[str] = mapped_column(String(128))
    file_path: Mapped[str] = mapped_column(String(256))
    tendering_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenders.id"))
    bargaining: Mapped[bool] = mapped_column(Boolean, default=False)
    file_hash: Mapped[str] = mapped_column(String(128))

    # relationship
    tender: Mapped["Tender"] = relationship(back_populates="bid_documents")


